<template>
  <div class="pad-20 bgc-default">
    <div class="pad-t-10 pad-l-20 pad-r-20 bg-color-white">
      <el-row class="hint-area" v-show="hintVisible">
        <el-col :span="18">
          <span class="pad-l-20">当前已【{{this.isShopAutoApprove === 1 ? '开启' : '关闭'}}】自动审核云店申请，可前往参数设置{{this.isShopAutoApprove === 1 ? '关闭' : '开启'}}。</span>
          <el-button type="text" @click="linkSetting">立即前往</el-button>
        </el-col>
        <el-col :span="6" align="right">
          <el-button type="info" icon="el-icon-close" class="hint-icon" circle @click="closeHint"></el-button>
        </el-col>
      </el-row>
      <div class="clearfix border-b">
        <div class="pad-t-15 pad-b-20 font-17 fl">
          <el-button @click="codeVisible = true" class="open-btn" type="primary">开通云店码</el-button>
          <span class="span-member pad-l-10">云店总数：<span class="span-member-1 font-red">{{ shopNumTotal }}个</span></span>
          <span class="span-member-2">|</span>
          <span class="span-member">待审核云店开通申请：<span class="span-member-1 font-red">{{ auditShopNum }}个</span></span>
          <span class="span-member-2">|</span>
          <span class="span-member">已开通云店：<span class="span-member-1 font-red">{{ useShopNum }}个</span></span>
        </div>
      </div>
      <!--顶部搜索 -->
      <div class="top-operate-default">
        <div class="search-item">
          <label>搜索申请：</label>
          <el-input @keyup.enter.native="handleSearch" v-model="searchListQuery.keyword" placeholder="请输入关键词" style="width: 300px"></el-input>
          <label class="mar-l-15">所属上级：</label>
          <el-select v-model="searchListQuery.partnerType" placeholder="所属上级类型">
            <el-option label="全部" value=""/>
            <el-option v-for="(val, key) in dict.partnerType" :key="key" :label="val" :value="key" />
          </el-select>
          <label class="mar-l-15">筛选时间：</label>
          <el-date-picker v-model="datePicker" type="daterange" unlink-panels range-separator="至" value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']" start-placeholder="开始时间" end-placeholder="结束时间"
          >
          </el-date-picker>
          <el-button-group>
            <el-button type="primary" @click="handleSearch" style="margin-left: 10px">查询</el-button>
            <el-button plain @click="resetSearch">重置</el-button>
          </el-button-group>
        </div>
      </div>
      <div class="tabs-box mar-t-15">
        <el-tabs type="card" v-model="searchListQuery.status" @tab-click="handleClick">
          <el-tab-pane :label="labels['0']" name="0"></el-tab-pane>
          <el-tab-pane :label="labels['1']" name="1"></el-tab-pane>
          <el-tab-pane :label="labels['2']" name="2"></el-tab-pane>
        </el-tabs>
      </div>
      <div class="mar-t-15 mar-b-15 v-align-c">
        <el-checkbox class="mar-l-14 mar-r-0" v-model="allChecked" @change="selectAll"><span class="mar-l-20">当页全选</span></el-checkbox>
        <span class="pad-l-4 pad-r-4">|</span>
        <div class="width-80">已选{{multipleSelection.length}}项</div>
        <el-button class="batch-btn" plain @click="batchUpdateStatus('1')" v-if="searchListQuery.status == 0">批量通过</el-button>
        <el-button class="batch-btn" plain @click="batchUpdateStatus('2')" v-if="searchListQuery.status == 0">批量拒绝</el-button>
        <el-button type="text" size="mini" @click="posterVisible = true" style="margin-left:20px;">设置申请云店海报</el-button>
      </div>
      <!-- 内容列表 -->
      <div class="table-container">
        <el-table ref="multipleTable" :data="dataList" @selection-change="handleSelectionChange" v-loading="listLoading" element-loading-text="加载中" style="width: 100%"
          header-cell-class-name="default-header" row-class-name="default-row">
          <el-table-column width="55px" type="selection"></el-table-column>
          <el-table-column width="380px" label="申请人信息">
            <template slot-scope="scope">
              <div @click="handleUpdate(scope.row)" class="flex v-align-c cursor-p">
                <label><img :src="scope.row.avatar" class="user-avatar"/></label>
                <div class="font-14 pad-l-10">
                  <div><span class="font-color-9">昵称：</span>{{ scope.row.nickname }}</div>
                  <div><span class="font-color-9">手机：</span>{{ scope.row.phone }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="320px" label="性质" v-if="searchListQuery.status == 1" prop="nature">
            <template slot-scope="scope">
              {{ dict.nature[scope.row.nature] }}
            </template>
          </el-table-column>
          <el-table-column width="320px" label="来源小程序" prop="appName" v-if="false">
          </el-table-column>
          <el-table-column width="320px" label="所属招募员" prop="recruiterName">
            <template slot-scope="scope">
              <div><span class="font-color-9">姓名：</span>{{scope.row.recruiterName}}</div>
              <div><span class="font-color-9">手机：</span>{{scope.row.recruiterPhone}}</div>
            </template>
          </el-table-column>
          <el-table-column width="320px" label="所属上级" prop="partnerType">
            <template slot-scope="scope">
              <div><span class="font-color-9">姓名：</span>{{ scope.row.partnerType == 3 ? scope.row.enterpriseName : scope.row.partnerName }}</div>
              <span><span class="font-color-9">类型：</span>{{ dict.partnerType[scope.row.partnerType] }}</span>
            </template>
          </el-table-column>
          <el-table-column width="320px" label="申请时间" prop="createTime"></el-table-column>
          <el-table-column width="140px" label="操作" fixed="right" align="right">
            <template slot-scope="scope">
              <template v-if="scope.row.status == '0'">
                <el-button type="text" size="medium" @click="handleAdopt(scope.row)">通过</el-button>
                <el-button type="text" size="medium" @click="handleRefuse(scope.row)">拒绝</el-button>
              </template>
              <template v-if="scope.row.status == '1'"><p>通过</p></template>
              <template v-if="scope.row.status == '2'"><p>拒绝</p></template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="searchListQuery.currentPage"
          :page-sizes="[10, 20, 50, 100]" :page-size="searchListQuery.size" layout="total, sizes, prev, pager, next, jumper" :total="total"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 云店申请码弹窗 -->
    <el-dialog title="总部云店申请码" class="code-area-box" :visible.sync="codeVisible" width="340px" :show-close="false" :close-on-click-modal="true">
      <div class="code-box">
        <img :src="shopWxaCode" v-if="shopWxaCode" />
      </div>
      <div slot="footer" class="dialog-footer">
        <p>用微信"扫一扫" 扫描上方二维码</p>
        <p>申请云店权限</p>
      </div>
    </el-dialog>

    <!-- 海报申请弹窗 -->
    <div class="poster-box">
      <el-dialog title="云店申请海报" width="320px" :before-close="handleCancelPoster" :visible.sync="posterVisible">
        <hr />
        <el-tag style="margin: 10px">建议图片宽度750px，高度跟随上传图片的高度变化</el-tag>
        <div class="content-area">
          <div class="img-box">
            <img :src="posterUrl" alt="" />
          </div>
          <div class="upload-btn-box">
            <el-upload action="/api/common/uploadFiles" name="files" :data="token" :show-file-list="false"
              v-loading="fileLoading" :on-success="handleUploadSuccess" :before-upload="beforeUpload">
              <el-button>上传海报</el-button>
            </el-upload>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleCancelPoster" size="mini">取 消</el-button>
          <el-button type="primary" @click="handleSavePoster" size="mini">保 存</el-button>
        </span>
      </el-dialog>
    </div>

    <!-- 提示关闭弹窗 -->
    <el-dialog title="确认操作" width="500px" v-el-drag-dialog :visible.sync="hintOperateVisible">
      <el-radio-group v-model="hintRadio">
        <el-radio label="0">今天不再显示</el-radio>
        <el-radio label="1">我已深知该业务功能配置，不再显示</el-radio>
      </el-radio-group>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hintOperateVisible = false">取消</el-button>
        <el-button type="primary" @click="saveHint">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  pagingEnterpriseShopApply,
  updateStatus,
  batchUpdateStatus,
  getEnterpriseShopApplyCode,
  getEnterpriseShopNum,
  statShopApplyByStatus,
  updateAutoApproveHint,
  updateShopPoster
} from '@/api/user/enterprise-shop-apply'
import { getByEnterpriseId } from '@/api/user/enterprise'
import { getDictByGroupName } from '@/api/common/common'
import { getToken } from '@/utils/auth'
import elDragDialog from '@/directive/el-dragDialog'

export default {
  directives: {
    elDragDialog
  },
  data() {
    return {
      total: null,
      listLoading: false,
      allChecked: false,
      // 云店码Visible
      codeVisible: false,
      // 自动审核Visible
      hintVisible: false,
      // 海报Visible
      posterVisible: false,
      // 自动审核操作Visible
      hintOperateVisible: false,
      fileLoading: false,
      labels: {
        0: '待审核(0)',
        1: '已通过(0)',
        2: '未通过(0)'
      },
      searchListQuery: {
        enterpriseId: this.getEnterpriseId(),
        currentPage: 1,
        size: 10,
        startDate: '',
        endDate: '',
        nature: '',
        status: '0',
        keyword: '',
        partnerType: ''
      },
      dict: {
        nature: {},
        partnerType: {}
      },
      token: '',
      dataList: [],
      datePicker: [],
      multipleSelection: [],
      hintRadio: '0',
      auditShopNum: '0',
      useShopNum: '0',
      shopNumTotal: '0',
      shopWxaCode: '',
      // 海报地址
      posterUrl: '',
      // 原始海报地址
      originPosterUrl: '',
      isShopAutoApprove: 0
    }
  },
  // 初始化页面
  created() {
    this.token = { accessToken: getToken() }
    this.initDict()
    this.initCardNum()
    this.initDataList()
    this.getEnterpriseShopApplyCode()
  },
  filters: {
  },
  methods: {
    // 初始化任务相关数据字典
    initDict() {
      getDictByGroupName('EnterpriseCardApplyDTO').then((response) => {
        if (response.isError) return
        Object.assign(this.dict, response.data)
      })
      getDictByGroupName('RecruiterDTO').then((response) => {
        if (response.isError) return
        Object.assign(this.dict, response.data)
      })
    },
    initCardNum() {
      getEnterpriseShopNum({ enterpriseId: this.getEnterpriseId() }).then((response) => {
        if (response.isError) return
        this.useShopNum = !response.data.useShopNum ? 0 : response.data.useShopNum
        this.shopNumTotal = !response.data.shopNumTotal ? 0 : response.data.shopNumTotal
      })
    },
    initDataList() {
      this.listLoading = true
      if (this.datePicker && this.datePicker.length > 0) {
        this.searchListQuery.startDate = this.datePicker[0]
        this.searchListQuery.endDate = this.datePicker[1]
      } else {
        this.searchListQuery.startDate = ''
        this.searchListQuery.endDate = ''
      }
      pagingEnterpriseShopApply(this.searchListQuery).then((response) => {
        this.total = response.data.total
        this.dataList = response.data.records
        this.listLoading = false
      })
      statShopApplyByStatus({ enterpriseId: this.getEnterpriseId() }).then((response) => {
        this.auditShopNum = response.data[0] || 0
        this.labels['0'] = '待审核(' + this.auditShopNum + ')'
        this.labels['1'] = '已通过(' + (response.data[1] || 0) + ')'
        this.labels['2'] = '未通过(' + (response.data[2] || 0) + ')'
      })
      getByEnterpriseId(this.getEnterpriseId()).then((response) => {
        if (response.isError) return
        this.hintVisible = response.data.shopAutoApproveHint === 1
        this.posterUrl = response.data.shopPosterUrl
        this.originPosterUrl = response.data.shopPosterUrl
        this.isShopAutoApprove = response.data.shopAutoApprove
      })
    },
    // 获取云店申请码
    getEnterpriseShopApplyCode() {
      getEnterpriseShopApplyCode({ enterpriseId: this.getEnterpriseId() }).then((response) => {
        this.shopWxaCode = response.data
      })
    },
    // tab点击事件
    handleClick() {
      this.handleSearch()
    },
    // 查询事件
    handleSearch() {
      this.searchListQuery.currentPage = 1
      this.initDataList()
    },
    // 重置事件
    resetSearch() {
      this.searchListQuery = {
        enterpriseId: this.getEnterpriseId(),
        startDate: '',
        endDate: '',
        nature: '',
        status: '0',
        currentPage: 1,
        size: 10,
        keyword: '',
        partnerType: ''
      }
      this.handleSearch()
    },
    // 批量通过/拒绝
    batchUpdateStatus(status) {
      const selections = this.multipleSelection
      if (selections.length === 0) {
        this.$message({ type: 'error', message: '请勾选数据!' })
        return
      }
      const array = []
      selections.forEach((e) => {
        array.push(e.applyId)
      })
      const data = {
        enterpriseId: this.getEnterpriseId(),
        applyIds: array,
        status: status
      }
      batchUpdateStatus(data).then((response) => {
        if (response.isError) return
        this.initDataList()
        this.initCardNum()
        this.$message({ type: 'success', message: '成功!' })
      })
    },
    // 通过
    handleAdopt(row) {
      this.$confirm('确认通过, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const applyId = row.applyId
        this.listLoading = true
        const data = {
          applyId: applyId,
          status: 1,
          enterpriseId: this.getEnterpriseId()
        }
        updateStatus(data).then((response) => {
          this.listLoading = false
          if (response.isError) return
          this.initDataList()
          this.initCardNum()
          this.$message({ type: 'success', message: '成功!' })
        })
      })
    },
    // 拒绝
    handleRefuse(row) {
      this.$confirm('拒绝通过, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const applyId = row.applyId
        const data = {
          applyId: applyId,
          status: 2,
          enterpriseId: this.getEnterpriseId()
        }
        updateStatus(data).then((response) => {
          this.initDataList()
          this.initCardNum()
          this.$message({ type: 'success', message: '成功!' })
        })
      })
    },
    // 勾选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 全选事件
    selectAll() {
      if (this.multipleSelection.length === 0 || this.multipleSelection.length < this.dataList.length) {
        this.dataList.forEach(item => {
          this.$refs.multipleTable.toggleRowSelection(item, true)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    // 跳转系统参数事件
    linkSetting() {
      this.$router.push({ path: '/system/system-config/index', query: { active: 'cloudshop-set' }})
    },
    // 自动审核提示框关闭事件
    closeHint() {
      this.hintRadio = '0'
      this.hintOperateVisible = true
    },
    // 自动审核提示框保存事件
    saveHint() {
      const form = {
        enterpriseId: this.getEnterpriseId(),
        hintSelectStatus: this.hintRadio
      }
      updateAutoApproveHint(form).then((response) => {
        if (response.isError) return
        this.hintVisible = false
        this.hintOperateVisible = false
      })
    },
    // 上传前事件
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isGIF = file.type === 'image/gif'
      const isPNG = file.type === 'image/png'
      const isBMP = file.type === 'image/bmp'
      if (!isJPG && !isGIF && !isPNG && !isBMP) {
        this.$message({ type: 'error', message: '上传图片必须是JPG/GIF/PNG/BMP 格式!' })
      } else {
        this.fileLoading = true
      }
      return (isJPG || isBMP || isGIF || isPNG)
    },
    // 上传成功后事件
    handleUploadSuccess(res, file) {
      this.fileLoading = false
      if (res.code === 101) {
        this.posterUrl = res.data[0]
      } else {
        this.$message({ type: 'error', message: res.msg })
        return false
      }
    },
    // 海报取消事件
    handleCancelPoster() {
      this.posterUrl = this.originPosterUrl
      this.posterVisible = false
    },
    // 海报保存事件
    handleSavePoster() {
      if (this.originPosterUrl === this.posterUrl) {
        this.posterVisible = false
        return
      }
      const form = {
        enterpriseId: this.getEnterpriseId(),
        shopPosterUrl: this.posterUrl
      }
      updateShopPoster(form).then((response) => {
        if (response.isError) return
        this.originPosterUrl = this.posterUrl
        this.posterVisible = false
        this.$message({ type: 'success', message: '保存成功!' })
      })
    },
    // 更改当前页数
    handleCurrentChange(val) {
      this.searchListQuery.currentPage = val
      this.initDataList()
    },
    // 更改当前页面大小
    handleSizeChange(val) {
      this.searchListQuery.size = val
      this.initDataList()
    }
  }
}
</script>

<style lang="less" scoped>
.span-member-1 {
  margin-left: 10px;
  margin-right: 10px;
}

.span-member-2 {
  margin-right: 10px;
}

.user-avatar {
  width: 59px;
  height: 59px;
  display: block;
  border-radius: 50px;
}
.poster-box {
  /deep/ .el-dialog__header {
    padding: 10px 10px 0px 10px;
    .el-dialog__headerbtn {
      top: 10px;
    }
  }
  /deep/ .el-dialog__body {
    hr {
      border-top: 0.5px solid #f2f2f2;
      transform: scaleY(0.5);
    }
  }
  /deep/ .el-dialog__title {
    text-align: left;
    font-weight: 600;
    font-size: 14px;
    padding: 0;
    color: #4f4f4f;
  }
  /deep/ .el-dialog__footer {
    text-align: center;
    .el-button {
      min-width: 0;
    }
  }
  .content-area {
    position: relative;
    .img-box {
      width: 100%;
      height: 360px;
      overflow-y: auto;
      padding-left: 10px;
      padding-right: 10px;
      img {
        width: 100%;
      }
    }
    .upload-btn-box {
      display: inline-block;
      width: 91.5%;
      text-align: center;
      color: #fff;
      position: absolute;
      bottom: 0;
      left: 10px;
      /deep/ .el-upload {
        width: 100%;
        .el-button {
          width: 100%;
          border-radius: 0;
          border: none;
          background: rgba(0, 0, 0, 0.5);
          padding: 15px;
          color: #fff;
        }
      }
    }
  }
}
.code-area-box {
  /deep/ .el-dialog {
    background: #409eff;
    border-radius: 10px;
  }
  /deep/ .el-dialog__title {
    color: #fff;
    font-size: 500;
  }
  .code-box {
    width: 90%;
    margin: 0 auto;
    text-align: center;
    border-radius: 10px;
    background: #ffffff;
    padding: 30px;
    img {
      width: 90%;
    }
  }
  .dialog-footer {
    color: #fff;
    text-align: center;
    p {
      margin: 0;
    }
  }
}
.hint-area {
  background-color: #fdf8c8;
  height: 45px;
  line-height: 45px;
  .hint-icon {
    padding: 1px;
    margin: 10px 10px 0 0;
  }
}
.el-radio-group {
  padding-left: 5%;
  .el-radio {
    padding-top: 15px;
    display: block;
  }
}
.open-btn{
  width: 95px;
  height: 38px;
  line-height: 38px;
  padding: 0;
  text-align: center;
}
</style>
